<!-- element-ui upload 上传组件 -->
<template>
  <div class="buttonBox">
    <!--
            action: 必填参数，上传的地址
            :auto-upload: 在选取文件后立即进行上传
            :show-file-list: 是否显示已上传文件列表-->
    <el-row>
      <ElCol :span="5">
        <el-upload
          action
          accept=".xlsx, .xls"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handle"
        >
          <el-button type="primary" slot="trigger">选取EXCEL文件</el-button>
        </el-upload>
      </ElCol>

      <el-button type="success" @click="submit">采集数据收集</el-button>
      <el-button type="success" @click="submitOut">导出选中的数据</el-button>
      <h2>插入成功 {{ num }} 条</h2>
    </el-row>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="sno" label="学号" width="120"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="120"> </el-table-column>
      <el-table-column prop="phone" label="电话" width="120"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
import xlsx from 'xlsx'
import { readFile, character } from '../util/util'
import axios from 'axios'
export default {
  data () {
    return {
      tableData: [],
      num: 0,
      SelectionList: []
    }
  },
  created () {
      this.getAll()
  },
  methods: {
    async getAll () {
      const { data } = await axios.get('http://192.168.3.9:3000/test/getall')

      this.tableData = data
    },
    handleSelectionChange (val) {
      this.SelectionList = val
    },
    //采集excel数据
    async handle (ev) {
      let file = ev.raw
      if (!file) return
      //读取file中的数据
      let data = await readFile(file)
      //用xlsx读取数据
      let workbook = xlsx.read(data, { type: 'binary' })
      //读取文件中第一个表的数据
      workbook = workbook.Sheets[workbook.SheetNames[0]]
      //读取到的文件转换为json格式
      data = xlsx.utils.sheet_to_json(workbook)
      //把读取出来的数据变为最后可以传递给服务器的数据
      let arr = []
      data.forEach(item => {
        let obj = {}
        for (let key in character) {
          if (!character.hasOwnProperty(key)) break
          let v = character[key]
          let text = v.text
          let type = v.type
          v = item[text] || ''
          type === 'string' ? (v = String(v)) : null
          type === 'number' ? (v = Number(v)) : null
          obj[key] = v
        }
        arr.push(obj)
      });
      this.tableData = arr
      console.log(arr);

    },
    submit () {
      if (this.tableData.length <= 0) {
        return this.$message.warning('请先选择excel文件')
      }
      //需要把数据一条条传递给服务器
      let n = 0
      let send = async () => {
        if (n > this.tableData.length - 1) {
          //都传完了
          return
        }
        let { data } = await axios.post('http://192.168.3.9:3000/test', this.tableData[n])
        console.log(data)
        if (data.code) {
          //成功
          this.num++
        }
        n++
        send()
      }
      send()
    },

    submitOut () {
      if (this.SelectionList.length <= 0) {
        this.$message.warning('请先选中数据')
        return
      }
      let arr = this.SelectionList.map((item) => {
        return {
          学号: item.sno,
          姓名: item.name,
          电话: item.phone
        }
      })
      let sheet = xlsx.utils.json_to_sheet(arr),    //json转换为sheet
        book = xlsx.utils.book_new()    //c创建表格
      xlsx.utils.book_append_sheet(book, sheet, '信息表')
      xlsx.writeFile(book, `user${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
